# 导出CSV功能模块
def export_table_to_csv(window, ui, aggregated=False):
    """
    将表格数据导出为CSV文件
    
    Args:
        ui: 界面实例，包含tableWidget表格
        aggregated: 是否是IP聚合模式的数据
    """
    try:
        import csv
        import os
        from PyQt5.QtWidgets import QFileDialog, QMessageBox
        
        # 获取表格
        table = ui.tableWidget
        
        # 检查表格是否有数据
        if table.rowCount() == 0:
            QMessageBox.warning(window, "导出失败", "表格中没有数据可导出！")
            return
        
        # 打开文件保存对话框
        file_path, _ = QFileDialog.getSaveFileName(
            window,
            "导出CSV文件",
            os.path.expanduser("~"),
            "CSV文件 (*.csv);;所有文件 (*)"
        )
        
        # 如果用户取消选择，直接返回
        if not file_path:
            return
        
        # 确保文件扩展名为.csv
        if not file_path.endswith('.csv'):
            file_path += '.csv'
        
        # 写入CSV文件
        with open(file_path, 'w', newline='', encoding='utf-8-sig') as csv_file:
            writer = csv.writer(csv_file)
            
            # 写入表头
            headers = []
            for col in range(table.columnCount()):
                header_item = table.horizontalHeaderItem(col)
                headers.append(header_item.text() if header_item else f"列{col+1}")
            writer.writerow(headers)
            
            # 写入表格数据
            for row in range(table.rowCount()):
                row_data = []
                for col in range(table.columnCount()):
                    item = table.item(row, col)
                    row_data.append(item.text() if item else "")
                writer.writerow(row_data)
        
        # 显示成功消息
        QMessageBox.information(window, "导出成功", f"数据已成功导出到:\n{file_path}")
        
    except Exception as e:
        # 显示错误消息
        QMessageBox.critical(window, "导出失败", f"导出CSV文件时发生错误:\n{str(e)}")
